package project.meetemup.bluetooth;


import java.util.Set;

import project.meetemup.R;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.widget.ArrayAdapter;

public class BlueToothManager extends Activity {
	
	private BluetoothAdapter btAdapter;
	private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    private ArrayAdapter<String> mNewDevicesArrayAdapter;
	private boolean isBlueToothAvailable;
	private boolean isBlueToothEnable;
	private static final int REQUEST_ENABLE_BT = 3;
	
	public BlueToothManager(){
		btAdapter = BluetoothAdapter.getDefaultAdapter();
		isBlueToothAvailable = true;
		isBlueToothEnable = true;
		
		if(btAdapter == null){
			isBlueToothAvailable = false;
			isBlueToothEnable = false;
		}
		else{
			isBlueToothEnable = btAdapter.isEnabled();
		}
	}
	
	public boolean isBlueToothAvailable() {
		return isBlueToothAvailable;
	}

	public boolean isBlueToothEnable() {
		return isBlueToothEnable;
	}
	
	public boolean enableBlueTooth(){
		if(!isBlueToothEnable){
			Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
	        startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
		}
		
		return isBlueToothEnable;
	}

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
       switch (requestCode) {
       case REQUEST_ENABLE_BT:
            // When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled, so set up a chat session
            	isBlueToothEnable = true;
                /**setupChat();**/
            } else {
                // User did not enable Bluetooth or an error occurred
                isBlueToothAvailable = false;
            }
        }
    }
    
    public void scan(){
    	mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_list);
    	mNewDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_list);

        Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();    	
    	
        if (pairedDevices.size() > 0) {
            /**findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);**/
            for (BluetoothDevice device : pairedDevices) {
                mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
            }
        } else {
            String noDevices = "No devices found";/**getResources().getText(R.string.none_paired).toString();**/
            mPairedDevicesArrayAdapter.add(noDevices);
        }    	
    }
    
    private void doDiscovery() {
        /**
         * If we're already discovering, stop it
         */
        if (btAdapter.isDiscovering()) {
        	btAdapter.cancelDiscovery();
        }

        /** 
         * Request discover from BluetoothAdapter
         */
        btAdapter.startDiscovery();
    }
    
}
